/**
 * @FileName: FeedbackController.java
 * @Author
 * @Description:
 * @Date 2016年10月5日 下午11:29:12
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.h5;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.H5ApiConstant;
import cn.hpclub.server.model.UserFeedback;

public class FeedbackController extends BaseH5Controller{
    private static Logger log = LoggerFactory.getLogger(FeedbackController.class);
    public void getMKOptions() throws IOException{
        String sql = " select sv.name,sv.code from sys_code_value sv LEFT JOIN" +
                " sys_code_type st ON st.id=sv.type_id WHERE st.`code`='GZMK' AND sv.is_deleted != 1";
        List<Record> list = Db.find(sql);

        List<JSONObject> options = new ArrayList<>();
        list.stream().forEach(record ->{
            JSONObject obj = new JSONObject();
            obj.put("value",record.getStr("name"));
            obj.put("key",record.getStr("code"));
            options.add(obj);
        });
        JSONObject json = new JSONObject();
        json.put("data",options);
        renderJson(json.toString());
    }


    public void add(){
        // 设置 header头，解决跨域问题
        // getResponse().setHeader("Access-Control-Allow-Origin", "*");
        JSONObject jo = setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, H5ApiConstant.Msg.FAIL, null);

        String token = getPara(H5ApiConstant.Ui.TOKEN, null);
        String userId = getPara("userId", null);
        String empCode = getPara("EmpCode", null);
        String orgId = getPara("storeId", null);
        String cityCode = getPara("CityCodeId", null);
        String type = getPara("type", null);
        String  moduleValue = getPara("moduleValue", null);
        String content = getPara("content", null);

        try{
            checkParams(userId, empCode, orgId, cityCode, type, content, token,moduleValue);
            if("1".equals(type)){
                moduleValue = null;
            }
            if(isUserValid(userId, token)){
                Record userInfo = getUserInfo(userId);
                saveFeedback(userId, empCode, orgId, cityCode, type, content, userInfo.getStr("name"),
                             userInfo.getStr("user_name"), getCityName(cityCode),moduleValue);
                jo = setResponseObj(H5ApiConstant.ResultCode.SUCCESS_CODE, H5ApiConstant.Msg.SUCCESS,
                                    H5ApiConstant.Msg.EMPTY);

            } else{
                jo = setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, H5ApiConstant.Msg.ILLEGAL_USER, null);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            jo = setResponseObj(H5ApiConstant.ResultCode.EXCEPTION_CODE, e.getMessage(), H5ApiConstant.Msg.EMPTY);
        }

        renderJson(jo.toString());
    }

    /**
     * @param token
     * @Title: checkParams
     * @Description:检查客户端输入参数
     * @param userId 用户ID
     * @param empCode 用户工号
     * @param orgId 用户所属机构ID
     * @param cityCode 用户所属城市ID
     * @param type 反馈类型
     * @param content 反馈内容
     * @throws IOException
     *             void
     */
    private void checkParams(String userId, String empCode, String orgId, String cityCode, String type, String content,
            String token,String moduleValue) throws IOException{
        if(StrKit.isBlank(token) || StrKit.isBlank(userId) || StrKit.isBlank(empCode) || StrKit.isBlank(orgId)
                || StrKit.isBlank(cityCode) || StrKit.isBlank(type) || StrKit.isBlank(content)){
            throw new IOException("参数错误，请检查输入参数");
        }
        if("0".equals(type) && StrKit.isBlank(moduleValue)){
            throw new IOException("参数错误，请检查输入参数");
        }

    }

    /**
     * @Title: getUserInfo
     * @Description:根据用户UserId用户用户信息
     * @param userId 用户ID
     * @return
     * @throws IOException
     *             Record
     */
    private Record getUserInfo(String userId) throws IOException{
        Record record = Db.findFirst("SELECT user_name, name FROM member_org WHERE id=?", userId);
        if(record == null){
            throw new IOException("参数错误，userId不存在");
        }
        return record;
    }

    /**
     * @Title: getCityName
     * @Description:根据城市ID获取城市名
     * @param cityCode 城市ID
     * @return
     * @throws IOException
     *             String
     */
    private String getCityName(String cityCode) throws IOException{
        Record cityRecord = Db.findFirst("SELECT region_name FROM cmcc_city WHERE region_id=?", cityCode);
        if(cityRecord == null){
            throw new IOException("参数错误，cityCode不存在");
        }

        String cityName = cityRecord.getStr("region_name");
        return cityName;
    }

    /**
     * @Title: saveFeedback
     * @Description:报讯反馈信息
     * @param userId 用户ID
     * @param empCode 用户工号
     * @param orgId 用户所属机构ID
     * @param cityCode 用户所在城市
     * @param type 反馈类型
     * @param content 反馈类容
     * @param name 用户姓名
     * @param phone 用户电话
     * @param cityName 城市名字
     *            void
     */
    private void saveFeedback(String userId, String empCode, String orgId, String cityCode, String type, String content,
            String name, String phone, String cityName,String moduleValue){
        UserFeedback model = getModel(UserFeedback.class);

        model.put("user_id", userId);
        model.put("emp_code", empCode);
        model.put("org_id", orgId);
        model.put("name", name);
        model.put("phone", phone);
        model.put("city_code", cityCode);
        model.put("city", cityName);
        model.put("type", type);
        model.put("content", content);
        model.put("time", new Date());
        model.put("state", 0);
        model.put("module_value", moduleValue);
        model.save();
    }
}
